<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="100%" @ok="handleSubmit">
    <div>
      <BasicForm @register="registerForm">
        <template #conditionName="{ model, field }">
          <div>

            <Ainput v-model:value="model[field]" :placeholder="'请选择' + model.label"
              @success="e => { handleSuccess1(e, model, field) }" v-if="model.conditionType == 1">
            </Ainput>
            <msDepartment v-model:value="model[field]" :placeholder="'请选择' + model.label"
              @success="e => { handleSuccess1(e, model, field) }" v-if="model.conditionType == 2">

            </msDepartment>
          </div>

        </template>
        <template #items="{ model, field }">
          <div style="height: 300px">
            <vxe-grid ref="tableRef" v-bind="gridOptions">
              <template #toolbar_buttons>
                <Button type="primary" @click="handleCreate">新增审批人</Button>
              </template>
              <template #action="{ row }">
                <TableAction outside :actions="getActions(row)" />
              </template>
            </vxe-grid>
          </div>

        </template>
      </BasicForm>
      <NodeUserModal @register="userModal[0]" @success="handleLoad"></NodeUserModal>
    </div>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { formSchema, node_columns, columns } from './menu.data';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { useDrawer } from '@/components/Drawer';

import Ainput from '@/views/bookManage/components/msAccount/Ainput.vue';
import msDepartment from '@/views/bookManage/components/msDepartment/msDepartment.vue';
import { TableAction } from '@/components/Table';
import { Button } from 'ant-design-vue';
import NodeUserModal from './NodeUserModal.vue';

import { saveSettingLine, settingNodeDelete, settingNodeList } from '@/api/sys/approval';
import { useModal } from "@/components/Modal";
import { BasicTableProps } from "@/components/VxeTable";
// import {departmentList} from "@/api/sys/msUser";
//import {columns, searchFormSchema} from "@/views/bookManage/components/msDepartment/account.data";
const userModal = useDrawer();

defineOptions({ name: 'MenuDrawer' });

const emit = defineEmits(['success', 'register']);

const isUpdate = ref(true);
const approvalSettingLineId = ref("");
const approvalSettingId = ref("");

const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { lg: 12, md: 24 },
});

const tableList = ref([]);//审批人列表

// insertTableDataRecord,deleteTableDataRecord,updateTableDataRecord


const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  approvalSettingLineId.value = "";
  approvalSettingId.value = "";
  // console.log("--data.record:",data.record);
  approvalSettingLineId.value = data.record.approvalSettingLineId;
  approvalSettingId.value = data.record.approvalSettingId;
  tableList.value = [];
  tableRef.value.reloadData([]);
  if (unref(isUpdate)) {

    setFieldsValue({
      ...data.record,
    });
    getUserList();
  } else {
    //setTableData([])
  }
  // const treeData = await getMenuList();
  // updateSchema({
  //   field: 'parentMenu',
  //   componentProps: { treeData },
  // });
});

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: node_columns,
  exportConfig: {},
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    enabled: false,
  },
  pagerConfig: {
    enabled: false,
  },
});


const getTitle = computed(() => (!unref(isUpdate) ? '新增审批链路' : '编辑审批链路'));


const tableRef = ref();


function getActions(record) {
  let arr = [
    {
      // icon: 'clarity:note-edit-line',
      label: '编辑',
      onClick: userEdit.bind(null, record),
    },
    {
      // icon: 'ant-design:delete-outlined',
      label: '删除',
      color: 'error',
      popConfirm: {
        title: '是否删除？',
        placement: 'left',
        confirm: userDelete.bind(null, record),
      },
    }
  ];


  return arr;
}


async function handleSubmit() {
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: true });
    // TODO custom api
    values.approvalSettingLineId = unref(approvalSettingLineId);
    values.approvalSettingId = unref(approvalSettingId);
    let t_list = tableRef.value.getTableData().tableData;
    values.items = t_list;
    // console.log(values);

    saveSettingLine(values).then(res => {
      closeDrawer();
      emit('success');
    });
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}

function handleSuccess1(e, model, field) {
  // console.log("_---e:",e)
  model[field] = e.names;
  model.conditionNo = e.ids;
}

function handleLoad(data) {
  // console.log("----handleLoad:", data);
  let i_isUpdate = data.isUpdate;
  let i_values = data.values;
  i_values.approvalSettingLineId = approvalSettingLineId.value;
  i_values.approvalSettingId = approvalSettingId.value;
  // let list = tableList.value;
  // list.push(data);
  let t_list = tableRef.value.getTableData().tableData;
  if (i_isUpdate) {
    // updateTableDataRecord(i_values.sort,i_values) t_list, i_values
    tableRef.value.setRow(i_values)
  } else {
    tableRef.value.insert(i_values);
    //   insertTableDataRecord(i_values);

  }
}

function handleCreate() {
  userModal[1].openDrawer(true, {
    isUpdate: false,
    record: {
      approvalSettingLineId: approvalSettingLineId.value,
      approvalSettingId: approvalSettingId.value
    }
  });
}
function userEdit(row) {
  userModal[1].openDrawer(true, {
    isUpdate: true,
    record: row
  });
}

function userDelete(row) {
  if (isUpdate.value) {
    settingNodeDelete(row).then(res => {
      if (res && res.code === 200) {
        getUserList();
      }
    })
  } else {
    tableRef.value.remove(row);
    //  deleteTableDataRecord(row);
  }

}

function getUserList() {
  if (isUpdate.value) {
    settingNodeList({ approvalSettingLineId: approvalSettingLineId.value }).then(res => {
      if (res && res.code === 200) {
        tableList.value = res.data;
        tableRef.value.reloadData(res.data);
        // setTableData(res.data);

      }
    })
  }

}

</script>
